package com.example.loginprojectbackend.filter;
import com.alibaba.fastjson.JSONObject;
import com.example.loginprojectbackend.pojo.Result;
import com.example.loginprojectbackend.utils.JwtUtils;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

@WebFilter(
        urlPatterns = {"/*"}
)
public class LoginCheckFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(LoginCheckFilter.class);

    public LoginCheckFilter() {
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        String url = req.getRequestURI().toString();
        log.info("请求的url：{}", url);
        if (!url.contains("login") && !url.contains("files") && !url.contains("download") && !url.contains("exportExcel") && !url.contains("reset")) {
            String jwt = req.getHeader("token");
            if (!StringUtils.hasLength(jwt)) {
                log.info("请求头token为空，返回未登录的信息");
                Result error = Result.error("NOT_LOGIN");
                String notLogin = JSONObject.toJSONString(error);
                resp.getWriter().write(notLogin);
            } else {
                try {
                    JwtUtils.parseJWT(jwt);
                } catch (Exception var11) {
                    var11.printStackTrace();
                    log.info("解析令牌失败，返回未登录错误信息");
                    Result error = Result.error("NOT_LOGIN");
                    String notLogin = JSONObject.toJSONString(error);
                    resp.getWriter().write(notLogin);
                    return;
                }

                log.info(jwt);
                log.info("令牌合法，放行");
                filterChain.doFilter(servletRequest, servletResponse);
            }
        } else {
            log.info("登陆操作，放行。。。");
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
